package com.halfsword.creativecraft.item.custom;

import net.minecraft.ChatFormatting;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class SpaceModeTurn extends Item {

        public SpaceModeTurn(Properties properties) {
                super(properties);
        }

        @Override
        public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
                ItemStack itemStack = player.getItemInHand(hand);

                if (!level.isClientSide() && player instanceof ServerPlayer serverPlayer) {
                        GameType currentMode = getPlayerGameMode(serverPlayer);
                        GameType newMode = (currentMode == GameType.CREATIVE) ? GameType.SURVIVAL : GameType.CREATIVE;

                        serverPlayer.setGameMode(newMode);
                        sendModeSwitchMessage(player, newMode);



                }

                return InteractionResultHolder.sidedSuccess(itemStack, level.isClientSide());
        }

        @Override
        public void appendHoverText(ItemStack stack, @Nullable Level level,
                                    List<Component> tooltip, TooltipFlag flag) {
                tooltip.add(Component.translatable("tooltip.creativecraft.space_mode_turn.tooltip")
                        .withStyle(ChatFormatting.AQUA));
                super.appendHoverText(stack, level, tooltip, flag);
        }

        private GameType getPlayerGameMode(ServerPlayer player) {

                if (player.getAbilities().instabuild) {
                        return GameType.CREATIVE;
                } else {
                        return GameType.SURVIVAL;
                }
        }

        private void sendModeSwitchMessage(Player player, GameType newMode) {
                String modeName = (newMode == GameType.CREATIVE)
                        ? I18n.get("gameMode.creative")
                        : I18n.get("gameMode.survival");

                Component message = Component.translatable("turn.creativecraft.tip1" )
                        .append(modeName)
                        .withStyle(newMode == GameType.CREATIVE
                                ? ChatFormatting.GOLD
                                : ChatFormatting.GREEN);

                player.sendSystemMessage(message);
        }
}